import {
  connectWebSocket
} from "../../utils/utils"
export default {
  namespaced: true,

  // 模块中的state数据
  state: () => ({
    token: uni.getStorageSync('token') || '',
    employeeInfo: JSON.parse(uni.getStorageSync('employeeInfo') || '{}')
  }),

  // 模块的mutations方法
  mutations: {
    // 更新token数据
    updateToken(state, token) {
      state.token = token
      this.commit('m_user/saveTokenToStorage')
    },
    // 更新用户数据
    updateEmployeeInfo(state, info) {
      state.employeeInfo = info
      this.commit('m_user/saveEmployeeInfo')
    },
    // 持久化token
    saveTokenToStorage(state) {
      console.log('进入了token的持久化操作')
      uni.setStorageSync('token', state.token)
      console.log('获得的token是', uni.getStorageSync('token'))
    },
    //持久化员工信息
    saveEmployeeInfo(state) {
      uni.setStorageSync('employeeInfo', JSON.stringify(state.employeeInfo))
    },
    // 清除所有数据
    clearUserInfo(state) {
      state.token = ''
      state.employeeInfo = {}
      uni.removeStorageSync('token')
      uni.removeStorageSync('employeeInfo')
    }
  },
  actions: {
    // 登录绑定
    async loginAndBind({
      commit,
      state,
      dispatch
    }, {
      employeeId,
      password,
      code
    }) {
      //  受到微信小程序的调用额度限制，这里先可以把获取的微信code进行数据的写死
      const [err, res] = await uni.login().catch(err => err)
      if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')

      const loginRef = await uni.$http.post('/login/wx', {
        employeeId,
        password,
        wxCode: res.code
      })
      const token = loginRef.data.data
      commit('updateToken', token);
      await dispatch('permission/initPermissions', null, {
        root: true
      })
      uni.switchTab({
        url: '/pages/my/my'
      })
    },
    // 登出操作
    async LoginOut({
      commit,
      state,
      dispatch
    }) {
      const [err, succ] = await uni.showModal({
        title: '提示',
        content: '确认退出登录吗？',
      }).catch(err => err)
      if (succ && succ.confirm) {
        await commit('clearUserInfo')
        uni.removeStorageSync('clockState')
        commit('m_clock/RESET_STATE', null, {
        root: true
      })
      }
      console.log('清空后的token为', state.token)
      uni.reLaunch({
        url: '/pages/my/my'
      })
    },
    async GetEmployeeList({
      commit,
      state
    }) {
      console.log('获取员工时token为', state.token)
      const res = await uni.$http.get('/getEmpInfo/personal')
      console.log(res.data.data)
      commit('updateEmployeeInfo', res.data.data)
      connectWebSocket()
    }
  },


  // 模块的getters
  getters: {
    // 目前这里就先设置拦截员工的设计,这里等会会删除的
    hasPermission(state) {
      return state.employeeInfo.role === '员工'
    }
  },
}